package com.ruoyi.test.serv.impl;

import com.ruoyi.test.dao.ChannelDao;
import com.ruoyi.test.domain.Channel;
import com.ruoyi.test.domain.common.Result;
import com.ruoyi.test.domain.common.ResultCodeEnum;
import com.ruoyi.test.dto.JoinChannelDto;
import com.ruoyi.test.exception.MyGuiguException;
import com.ruoyi.test.serv.IChannelServ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;


@Service
@Transactional
public class IChannelServImpl implements IChannelServ {
    @Autowired
    private ChannelDao dao;

    @Override
    public Result<List<Channel>> getAllChannel() {
        List<Channel> channel = dao.getAllChannel();
        return Result.build(channel, ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result add(Channel channel) {
        List<Channel> dbChannel = dao.getAllChannel();
        dbChannel.forEach(item -> {
            if (item.getName().equals(channel.getName())) { // 如果数据库中已经有了，则返回成功
                throw new MyGuiguException(ResultCodeEnum.CHANNEL_NAME_IS_EXISTS);
            }
        });

        List<Channel> deletedDbChannel = dao.getAllDeletedChannel();
        AtomicBoolean isDeleted = new AtomicBoolean(false);
        deletedDbChannel.forEach(item -> {
            if (item.getName().equals(channel.getName())) { // 如果数据库中已经有了且被删除了，则返回成功
                isDeleted.set(true);
            }
        });

        if (isDeleted.get()) {
            dao.addForUpdate(channel);
        } else {
            dao.add(channel);
        }


        return Result.build(null, ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result<List<String>> getAllUserByChannelName(String channelName) {
        List<String> userList = dao.getAllUserByChannelName(channelName);
        return Result.build(userList, ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result joinChannel(JoinChannelDto joinChannelDto) {
        System.out.println("joinChannelDto" + joinChannelDto);
        List<Long> ids = dao.getUserAndChannel(joinChannelDto);
        if (ids.isEmpty()) {
            dao.joinChannelForInsert(joinChannelDto);
        } else {
            dao.joinChannelForUpdate(joinChannelDto);
        }
        return Result.build(null, ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result exitChannel(JoinChannelDto joinChannelDto) {
        dao.exitChannel(joinChannelDto);
        return Result.build(null, ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result removeChannel(String channelName) {
        dao.removeChannel(channelName);
        return Result.build(null, ResultCodeEnum.SUCCESS);
    }


}
